package com.chainyoung.component_tmmarket.ui;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.chainyoung.common.appcommon.entity.HdWalletTokenTransaction;
import com.chainyoung.common.appcommon.entity.MarketDetail;
import com.chainyoung.common.base.BaseFragment;
import com.chainyoung.common.bean.ReqModel;
import com.chainyoung.common.di.AppComponent;
import com.chainyoung.common.event.BaseEvent;
import com.chainyoung.common.http.JsonConventUtils;
import com.chainyoung.common.http.websocket.WebSoketUtils;
import com.chainyoung.common.http.websocket.WsManager;
import com.chainyoung.common.http.websocket.WsStatus;
import com.chainyoung.common.http.websocket.WsStatusListener;
import com.chainyoung.component_tmmarket.R;
import com.chainyoung.component_tmmarket.R2;
import com.chainyoung.component_tmmarket.adapter.MarketListAdapter;

import com.chainyoung.component_tmmarket.di.DaggerTradeMarketComponent;
import com.chainyoung.component_tmmarket.di.TradeMarketModule;
import com.chainyoung.component_tmmarket.mvp.contract.MarketListContract;
import com.chainyoung.component_tmmarket.mvp.presenter.MarketListPresenter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.simple.eventbus.EventBus;
import org.simple.eventbus.Subscriber;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import butterknife.BindView;
import okhttp3.Response;
import okio.ByteString;


public class MarketListFragment extends BaseFragment<MarketListPresenter> implements MarketListContract.View {


    @BindView(R2.id.txt_trade_amount)
    TextView txtTradeAmount;
    @BindView(R2.id.txt_newest_price)
    TextView txtNewestPrice;
    @BindView(R2.id.txt_day_change)
    TextView txtDayChange;
    @BindView(R2.id.rv_list)
    RecyclerView rvList;


    private String TAG = getClass().getSimpleName();

    private MarketListAdapter mAdapter;

    private List<MarketDetail> detailList = new ArrayList<>();

    private WsManager wsManager;
    private String currencyName;//市场币名称
    private boolean isAlreadySubed = false;
    private boolean isVisiable;
    private int selectPosition;
    private SimpleDateFormat dfs = new SimpleDateFormat("yyyy-MM-dd HH:mm");


    public static MarketListFragment newInstance(String currency) {
        MarketListFragment fragment = new MarketListFragment();
        Bundle args = new Bundle();
        args.putString("currencyName", currency);
        fragment.setArguments(args);
        return fragment;
    }

    public void setCurrencyName(String currencyName) {
        this.currencyName = currencyName;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        if (getArguments() != null) {
            currencyName = getArguments().getString("currencyName");
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerTradeMarketComponent.builder()
                .appComponent(appComponent)
                .tradeMarketModule(new TradeMarketModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void initUi() {
        super.initUi();
        mAdapter = new MarketListAdapter(detailList, currencyName);
        rvList.setAdapter(mAdapter);
        rvList.setLayoutManager(new LinearLayoutManager(mContext));
        mAdapter.notifyDataSetChanged();
        wsManager = WebSoketUtils.getWsManager();
    }


    @Override
    protected boolean useLoadSir() {
        return true;
    }

    @Override
    protected void onPageRetry(View v) {
        super.onPageRetry(v);
    }

    @Override
    protected void initData() {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.tmmarket_fragment_market_list;
    }


    @Override
    protected void onFirstUserVisible() {

        getHttpMarketList();

        isVisiable = true;
        wsManager.setWsStatusListener(new WsStatusListener() {

            @Override
            public void onMessage(ByteString bytes) {
                super.onMessage(bytes);
                String r = JsonConventUtils.byteBufferToString(bytes.asByteBuffer());
                try {
                    String result = JsonConventUtils.uncompress(r);
                    handleResult(result);
                    Log.d(TAG, result);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                EventBus.getDefault().post(new BaseEvent<>(BaseEvent.EventCode.WS_OPEN));
            }

            @Override
            public void onFailure(Throwable t, Response response) {
                isAlreadySubed=false;
                super.onFailure(t, response);
                Log.d(TAG, "closed");
            }

            @Override
            public void onOpen(Response response) {
                super.onOpen(response);
                EventBus.getDefault().post(new BaseEvent<>(BaseEvent.EventCode.WS_OPEN));
            }
        });

    }


    @Override
    public void onUserVisible() {
        super.onUserVisible();
        isVisiable = true;
        if (wsManager.getCurrentStatus() != WsStatus.CONNECTED) {
            wsManager.startConnect();
        }
    }

    @Override
    public void onUserInvisible() {
        super.onUserInvisible();
        if (wsManager.getCurrentStatus() == WsStatus.CONNECTED) {
            ReqModel reqModel1 = new ReqModel();
            reqModel1.setType("unsub");
            reqModel1.setTopic(getMarketName());
            wsManager.sendMessage(new Gson().toJson(reqModel1));
            isAlreadySubed = false;
        }
        isVisiable = false;
    }


    public void getMarketList() {
        ReqModel reqModel = new ReqModel();
        reqModel.setType("sub");
        reqModel.setTopic(getMarketName());
        wsManager.sendMessage(new Gson().toJson(reqModel));

        ReqModel reqModel1 = new ReqModel();
        reqModel1.setType("req");
        reqModel1.setTopic(getMarketName());
        wsManager.sendMessage(new Gson().toJson(reqModel1));
        isAlreadySubed = true;
    }


    private void handleResult(String marketResult) {

        Gson gson = new Gson();
        Map<String, Object> map = new HashMap<String, Object>();
        Map<String, Object> map1 = new HashMap<String, Object>();
        Map<String, Object> map2 = new HashMap<String, Object>();
        map = gson.fromJson(marketResult, map.getClass());
        if (map.containsKey("type") && map.get("type").equals("ping")) {
            //发送pong
            sendPong();
        }
        if (map.containsKey("tick")) {
            map1 = (Map<String, Object>) map.get("tick");
            if (map1.containsKey(currencyName.toLowerCase())) {
                map2 = (Map<String, Object>) map1.get(currencyName.toLowerCase());
            }
        }
        List mdata = new ArrayList();
        for (Map.Entry<String, Object> entry : map2.entrySet()) {
            MarketDetail marketDetail;
            marketDetail = new Gson().fromJson(new Gson().toJson(entry.getValue()), MarketDetail.class);
            marketDetail.setName(entry.getKey());
            mdata.add(marketDetail);
            Log.d("market   ", "key= " + entry.getKey() + " and value= "
                    + entry.getValue());
        }
        if (!mdata.isEmpty()) {
            detailList.clear();
            detailList.addAll(mdata);
            showPageContent();
        }
        mAdapter.notifyDataSetChanged();

    }

    private void sendPong() {
        ReqModel reqModel = new ReqModel();
        reqModel.setType("pong");
        wsManager.sendMessage(new Gson().toJson(reqModel));
    }


    private String getMarketName() {
        return "market." + currencyName.toLowerCase() + ".market";
    }


    //---------------------------------http请求--------------------------------------
    private void getHttpMarketList() {
        TreeMap<String, Object> map = new TreeMap<>();
        map.put("region", currencyName.toLowerCase());
        mPresenter.getMarketList(map);
    }

    @Override
    public void showMarketList(String data) {
        Gson gson = new Gson();
        Map<String, HashMap<String, MarketDetail>> map = gson.fromJson(data, new TypeToken<HashMap<String, HashMap<String, MarketDetail>>>() {
        }.getType());
        if (map.containsKey(currencyName.toLowerCase())) {
            if (!map.get(currencyName.toLowerCase()).isEmpty()) {
                detailList.clear();
                for (Map.Entry<String, MarketDetail> entry : map.get(currencyName.toLowerCase()).entrySet()) {
                    MarketDetail marketDetail = entry.getValue();
                    marketDetail.setName(entry.getKey());
                    detailList.add(marketDetail);
                }
                mAdapter.notifyDataSetChanged();
            }
        }

    }

    // ---------------------------------event-------------------------------------

    @Subscriber
    public void onGetMarketList(BaseEvent event) {
        if (event.getCode() == BaseEvent.EventCode.WS_OPEN) {
            if (isVisiable && mIsPrepared && !isAlreadySubed) {
                getMarketList();
            }
        }

    }


}
